package db;

import java.util.Calendar;
import java.util.Date;

import util.MyLogger;


/**
 * This class performs regular jobs on the database. Tasks are:
 * - Send E-Mails (round about midnight) with people having birthday within the user selected info period
 * - 
 * @author Kristin Behrens, Robin Gawenda, Swen Jung
 *
 */
public class DBDaemon extends MyLogger implements Runnable {

	protected static DBDaemon daemon=null;
	protected Thread thread=null;
	protected Date lastTimeSent=null;
	protected long day=24*60*60;
	
	protected DBDaemon(){
		thread=new Thread();
		thread.setDaemon(true);
		thread.start();
	}
	
	@Override
	public void run() {
		while(true){
			if(performMailWork()){
				//send E-Mails with Birthdays upcoming
				
			}
			try {
				synchronized (this) {
					wait(day);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}	
		}
	}
	
	protected int sendMails(){
		int sentMails=-1;
		//get data for upcoming birthdays and prepare to send e-mails
		
		return sentMails;
	}
	
	protected boolean performMailWork(){
		Date date=new Date();
		
		//Normalize the current date to the first millisecond of the day
		long mod=day;
		mod=date.getTime()%(mod);
		mod=date.getTime()-mod;
		date.setTime(mod);
		
		Calendar cal= Calendar.getInstance();
		cal.setTime(new Date());
		
		//between 12 pm and 2 am and if not already sent 
		return cal.get(Calendar.HOUR_OF_DAY)>=0&&cal.get(Calendar.HOUR_OF_DAY)<=1&&date!=lastTimeSent;
	}
	
	public static DBDaemon getInstance(){
		if(daemon==null){
			daemon=new DBDaemon();
		}
		return daemon;
	}
}
